<template>
  <div ref="chart"></div>
</template>

<script>
import * as d3 from "d3";

export default {
  data() {
    return {
      data: [
        {x: 50, y: 50},
        {x: 150, y: 150},
        {x: 250, y: 100},
      ],
    };
  },
  mounted() {
    this.renderChart();
  },
  methods: {
    renderChart() {
      const svg = d3
        .select(this.$refs.chart)
        .append("svg")
        .attr("width", 100)
        .attr("height", 100);

      svg
        .selectAll("circle")
        .data(this.data)
        .enter()
        .append("circle")
        .attr("cx", (d) => d.x)
        .attr("cy", (d) => d.y)
        .attr("r", 10)
        .style("fill", "steelblue")
        .style("cursor", "move")
        .call(
          d3
            .drag()
            .on("start", (event, d) => this.dragStarted(event, d))
            .on("drag", (event, d) => this.dragged(event, d))
            .on("end", (event, d) => this.dragEnded(event, d))
        );
    },
    dragStarted(event, d) {
      d3.select(event.sourceEvent.target).raise().classed("active", true);
    },
    dragged(event, d) {
      d.x = event.x;
      d.y = event.y;
      d3.select(event.sourceEvent.target).attr("cx", d.x).attr("cy", d.y);
    },
    dragEnded(event, d) {
      d3.select(event.sourceEvent.target).classed("active", false);
    },
  },
};
</script>

<style>
.active {
  stroke: #000;
  stroke-width: 2px;
}
svg {
  border: 1px solid #000;
}
</style>
